<?php defined('SYSPATH') or die('No direct script access.');

class Model_Services_SportPatient extends Model implements Jqgrid_GridListener{
	
	public $id_patient;
	public $sport_patient = NULL;
	
	public function __construct($id=false){
		$this->id_patient = $id;
	}	
	
	public function count($criteria = false){
		return ORM::factory("dao_sportpatient")->where("patient_id","=",$this->id_patient)->count_all();
	}
	
	public function getList($criteria = false){
			
		if (!$criteria)	$sport_patient_list = ORM::factory("dao_sportpatient")->where("patient_id","=",$this->id_patient)->find_all()->as_array();
		else $sport_patient_list = ORM::factory("dao_sportpatient")->where("patient_id","=",$this->id_patient)->order_by($criteria->sidx,$criteria->sord)->limit($criteria->limit)->offset($criteria->calcOffset())->find_all()->as_array();
	
		$dataset = array();
		foreach ($sport_patient_list as $sport_patient){
			$dataset[$sport_patient->id] = array(	$sport_patient->sport->sport_name,
													Helper_Service::factory("patient",$this->id_patient)->getAge() - $sport_patient->age_at_start,
													$sport_patient->hours_by_week,
													$sport_patient->patient_id);
		}
				
		return $dataset;
	}	
		
	public function getCondition($orderfield, $ordertype, $start,$limit){
		return ORM::factory("dao_sportpatient")->where("patient_id","=",$this->id_patient)->order_by($orderfield,$ordertype)->limit($limit)->find_all()->as_array();
	}
		
	public function get($id){
		return ORM::factory("dao_sportpatient")->find($id);
	}
		
	public function save($id, array $data){
		
		$this->sport_patient = ($id) ? ORM::factory("dao_sportpatient",$id) : ORM::factory("dao_sportpatient");
		
		//hacer funcion para pasar de string a numeros (una funcion sanitize input)
		$this->sport_patient->sport_id = intval($data['sport_id']);
		$this->sport_patient->patient_id = ($id) ? intval($data['patient_id']) : $this->id_patient;
		$this->sport_patient->age_at_start = intval($data['age_at_start']);
		//$this->sport_patient->age_at_stop = intval($data['age_at_stop']);
		$this->sport_patient->hours_by_week = intval($data['hours_by_week']);
				
		$this->sport_patient->save();
		return $this->sport_patient->id;
	}

	public function delete($id){
		$this->sport_patient = ORM::factory("dao_sportpatient",$id);
		$this->sport_patient->delete();
		return $id;
	}	
	
	public function getPatientSports($id=false){
		return ORM::factory("dao_sportpatient")->where("patient_id","=",(!$id)?$this->id_patient:$id)->find_all()->as_array();
	}
	
}
?>
